﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class ConstantRule : ILRule<ConstantHandle>
    {
        [ILInfo]
        public EntityHandle Parent { get; }

        [ILInfo(ILInfoParseMethod.AsString)]
        public object Value { get; }

        [ILInfo(true)]
        public ConstantTypeCode TypeCode { get; }

        [ILInfo]
        public byte[] ByteValue { get; }

        public ConstantRule(
            EntityHandle parent,
            object value)
            : base()
        {
            Parent = parent;
            Value = value;
        }

        public ConstantRule(MetadataReader reader, ConstantHandle constantHandle)
            : base(reader)
        {
            Constant constant = reader.GetConstant(constantHandle);
            Parent = constant.Parent;
            TypeCode = constant.TypeCode;
            ByteValue = reader.GetBlobBytes(constant.Value);
        }

        public override ConstantHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddConstant(
                parent: Parent,
                value: Value);
        }
    }
}